import React from 'react';
import { withRouter, Redirect } from 'react-router-dom'
import { Toast } from 'antd-mobile';
import api from '@MODULES/common/api'
import './css/HandeGetPhoneCode.less'

class HandeGetPhoneCode extends React.PureComponent {


    constructor(props) {
        super(props)
        this.state = {
            initialization: true,
            getPhoneCodeInfo: '获取验证码',
            seconds: 60,
            isGetPhoneCode: false
        }
    }

    componentWillUnmount() {
        this.interval && clearInterval(this.interval)
    }


    render() {
        return (
            <button disabled={this.state.isGetPhoneCode} onClick={() => {
                if (this.props.onClick) {
                    this.props.onClick()
                }
                this.handeGetPhoneCode()
            }} id="HandeGetPhoneCode" className={this.props.className}>
                {this.state.getPhoneCodeInfo}
            </button>
        );
    }


    // 获取手机验证码
    handeGetPhoneCode() {
        // mobile type
        var params = this.props.params
        if (this.state.isGetPhoneCode) {
            return
        }
        if (!params.notVerify) {
            if (!params.phone) {
                Toast.info('请填写手机号', 1)
                return
            }
            params.phone = params.phone.replace(/\s+/g, "")
            const mobileRule = /(?:^1[3456789]|^9[28])\d{9}$/
            if (!mobileRule.test(params.phone)) {
                Toast.info('手机号格式不正确', 1)
                return
            }
        }
        this.setState({
            isGetPhoneCode: true,
            seconds: 60
        })

        this.interval && clearInterval(this.interval)
        api.phoneSendCode(params, {
            success: (data) => {
                Toast.success('验证码已发送', 1)
                if (data.vef_code) {
                    window.alert('您的短信验证码内容为：' + data.vef_code)
                }
                this.interval = setInterval(() => {
                    let seconds = this.state.seconds - 1
                    if (seconds >= 0) {
                        this.setState({ seconds, getPhoneCodeInfo: `${seconds}秒后获取` })
                    } else {
                        this.setState({ isGetPhoneCode: false, getPhoneCodeInfo: '获取验证码' })
                    }
                }, 1000)
            },
            error: () => {
                this.interval && clearInterval(this.interval)
                this.setState({ isGetPhoneCode: false, getPhoneCodeInfo: '获取验证码' })
                console.log("手机号已注册")
            }
        })
    }
}

export default withRouter(HandeGetPhoneCode)